﻿using AutoMapper;
using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Write.API.Command.ApplyCommand;
using MediatR;

namespace B.S.BaseData.Write.API.CommandHandler.ApplyHandler
{
    public class AddAppHandler : IRequestHandler<AddAppCommand, APIResult<object>>
    {
        private readonly IBaseRepository<Apply> _ApplyRepository;
        private readonly IBaseRepository<RecordSheet> _RecordRepository;

        public AddAppHandler(IBaseRepository<Apply> applyRepository, IBaseRepository<RecordSheet> recordRepository)
        {
            _ApplyRepository = applyRepository;
            _RecordRepository = recordRepository;
        }

        public async Task<APIResult<object>> Handle(AddAppCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = APIEnum.Success;
            result.Msg = "添加成功";

            Apply apply = new Apply();

            #region 申请表

            apply.ApplyPerson = request.Name;
            apply.DepartmentId = request.DepartmentId;
            apply.LeaveType = request.LeaveType;
            apply.fristTime = request.fristTime;
            apply.EndTime = request.endTime;
            apply.TotalTime = request.TotalTime;
            apply.CheckTime = request.CheckTime;
            apply.Reason = request.Reason;
            apply.UpUserId = request.UpUserId;
            apply.ApprovalStatusId = (int)ApprovalStatus.待审核;
            apply.ApprovalStatusName = ApprovalStatus.待审核.ToString();
            apply.CreateUser = request.Name;
            apply.CreateTime = DateTime.Now;
            apply.UpdateTime = null;
            apply.UpdateUser = "";
            apply.YuanYin = "";
            apply.is_load = "";

            _ApplyRepository.Add(apply);
            #endregion
            #region 审批记录表
            RecordSheet record = new RecordSheet();
            record.ApplyId = apply.ApplyId;
            
            record.NodeName = "申请";
            record.OperatorId = request.UserId;
            record.OperatorName = request.Name;
            record.OperatorOpinion = "";
            record.RecordStatusId = (int)RecordStatus.已提交;
            record.RecordStatusName = RecordStatus.已提交.ToString();
            record.CreateTime = DateTime.Now;
            _RecordRepository.Add(record);
            #endregion

            return await Task.FromResult(result);
        }
    }
}
